using System;
using System.Collections.Generic;
using System.IO;
using System.Threading;
using Seagull.Configuration;
using Seagull.DAL;

namespace Seagull.Jobs
{
    public class CleanupJob : MaintenanceJob
    {
        private readonly DateTime _startTime;

        readonly PathHelper _sourceDataPathHelper = new PathHelper(
            Config.Instance.PathConfig.SourceDataFolder, Config.Instance.PathConfig.DataFileExtension);

        readonly PathHelper _sourceLogPathHelper = new PathHelper(
            Config.Instance.PathConfig.SourceLogFolder, Config.Instance.PathConfig.DataFileExtension);

        readonly PathHelper _compressedDataPathHelper = new PathHelper(
            Config.Instance.PathConfig.CompressDataFolder, Config.Instance.PathConfig.CompressedFileExtension);

        readonly PathHelper _compressedLogPathHelper = new PathHelper(
            Config.Instance.PathConfig.CompressLogFolder, Config.Instance.PathConfig.CompressedFileExtension);

        public CleanupJob(DateTime startTime)
        {
            _startTime = startTime;
        }

        public override void Start(CancellationToken cancellationToken)
        {
            CleanupDateDirs(_sourceDataPathHelper.DateDirectories, DateTime.Today.AddDays(-Config.Instance.TaskConfig.RawDataKeptDays - .5));
            CleanupDateDirs(_sourceLogPathHelper.DateDirectories, DateTime.Today.AddDays(-Config.Instance.TaskConfig.RawLogKeptDays - .5));
            CleanupDateDirs(_compressedDataPathHelper.DateDirectories, _startTime);
            CleanupDateDirs(_compressedLogPathHelper.DateDirectories, _startTime);
        }

        private static void CleanupDateDirs(IEnumerable<Tuple<DirectoryInfo, DateTime>> dateDirectories, DateTime startTime)
        {
            foreach(var dateDirectory in dateDirectories)
            {
                if(dateDirectory.Item2 < startTime)
                {
                    dateDirectory.Item1.Delete(true);
                }
            }
        }
    }
}